﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class RoleMenuAddCommandHandler : IRequestHandler<RoleMenuAddCommand, APIResult<object>>
    {
        private readonly IBaseRepository<RoleMenuModel> _roleRepository;

        public RoleMenuAddCommandHandler(IBaseRepository<RoleMenuModel> roleRepository)
        {
            _roleRepository = roleRepository;
        }

        public async Task<APIResult<object>> Handle(RoleMenuAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.AddSuccess;
            result.Message = APIEnum.AddSuccess.Desc();
            List<int> MenuId=request.MenuId.Split(',').Select(x=>Convert.ToInt32(x)).ToList();
            var list = _roleRepository.GetAll().Where(x => x.RID == request.RoleId);
            if (list.Count() > 0) 
            {
                foreach (var item in list)
                {
                    _roleRepository.Del(item);
                }
            }
            
            foreach (var item in MenuId)
            {
                RoleMenuModel roleMenu = new RoleMenuModel()
                {
                    RID=request.RoleId,
                    MID=item
                };
                await _roleRepository.Add(roleMenu);
            }
            return await Task.FromResult(result);
        }
    }
}
